#!/bin/bash

# 检测系统使用的包管理器，返回标准化名称
# 返回值：apt | dnf | yum | pacman | zypper | apk | emerge | unknown
pmDetect() {
    # 优先按命令存在性判断（顺序）
    if command -v apt >/dev/null 2>&1 || command -v apt-get >/dev/null 2>&1; then
        echo "apt"
        return
    elif command -v dnf >/dev/null 2>&1; then
        echo "dnf"
        return
    elif command -v yum >/dev/null 2>&1; then
        echo "yum"
        return
    elif command -v pacman >/dev/null 2>&1; then
        echo "pacman"
        return
    elif command -v zypper >/dev/null 2>&1; then
        echo "zypper"
        return
    elif command -v apk >/dev/null 2>&1; then
        echo "apk"
        return
    elif command -v emerge >/dev/null 2>&1; then
        echo "emerge"
        return
    fi

    # 备用：通过 /etc/os-release 推断
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        case "${ID}" in
            ubuntu|debian|linuxmint|kali|pop)
                echo "apt"
                ;;
            fedora|rhel|centos|rocky|almalinux)
                # 进一步判断是 dnf 还是 yum（基于版本）
                if [[ "${VERSION_ID:-}" =~ ^[89]|^[1-9][0-9] ]]; then
                    echo "dnf"  # RHEL/CentOS 8+
                else
                    echo "yum"  # 默认为 yum（如 CentOS 7）
                fi
                ;;
            arch|manjaro)
                echo "pacman"
                ;;
            opensuse*|suse)
                echo "zypper"
                ;;
            alpine)
                echo "apk"
                ;;
            gentoo)
                echo "emerge"
                ;;
            *)
                echo "unknown"
                ;;
        esac
    else
        echo "unknown"
    fi
}

# 从文本文件中读取包列表，输出为空格分隔的字符串
# 用法：PKGS=$(getPackagesFromFile "/path/to/packages.txt")
readPackagesFromFile() {
    local filePath="$1"

    # 检查参数是否提供
    if [[ -z "${filePath}" ]]; then
        echo "错误：未提供文件路径" >&2
        return 1
    fi

    # 检查文件是否存在
    if [[ ! -f "${filePath}" ]]; then
        echo "错误：文件未找到：${filePath}" >&2
        return 1
    fi

    # 检查文件是否可读
    if [[ ! -r "${filePath}" ]]; then
        echo "错误：指定文件不可读：${filePath}" >&2
        return 1
    fi

    # 读取文件，过滤空行和空白行，输出为单行空格分隔
    local packages
    packages=$(awk 'NF && /^[[:space:]]*[^#[:space:]]/ {gsub(/^[[:space:]]+|[[:space:]]+$/, ""); print}' "${filePath}" | tr '\n' ' ' | sed 's/ $//')

    # 输出包列表
    echo "$packages"
}